<script>
import {doDelete, doGet, doPost, doPut} from "../../http/httpRequest.js";
import {msgConfirm, msgTip} from "../../util/util.js";

export default {
  name: "DictDetailView",
  inject:['reload'],
  data(){
    return {
      dictValues:[],
      dictType:{},
      selectedRows: [],
      dialogTitle: "",
      addDictValueDialogVisible: false,
      dictValue: {
        typeId: ''
      },
      dictValueRules: {
        value: [
          { required: true, message: "请输入数据字典项", trigger: "blur" },
          { validator: this.validateDictValue, trigger: "blur" }
        ],
        desc: [
          { required: true, message: "请输入数据字典项描述", trigger: "blur" }
        ]
      }
    }
  },
  methods:{
    getDictValues() {
      const id = this.$route.params.id;
      doGet("/system/dict/value/type/" + encodeURI(id)).then(resp => {
        if (resp.data.code === 200) {
          this.dictValues = resp.data.data;
        } else {
          msgTip("获取数据字典项失败","error");
        }
      });
    },
    getDictType() {
      const id = this.$route.params.id;
      doGet("/system/dict/" + encodeURI(id)).then(resp => {
        if (resp.data.code === 200) {
          this.dictType = resp.data.data;
        } else {
          msgTip("获取数据字典失败","error");
        }
      });
    },
    batchDelDictType() {
      // TODO: 批量删除逻辑
      msgConfirm("确定要删除吗？").then(()=>{
        const ids = this.selectedRows.join(",");
        doDelete("/system/dict/value/batchDelete",{ ids : ids }).then(resp => {
          if(resp.data.code === 200) {
            msgTip("删除成功","success");
            this.reload();
          }
        })
      }).catch(() => {
        msgTip("取消了删除", 'warning');
      })
    },
    addValue() {
      // TODO: 新增逻辑
      console.log("addValue")
      this.dialogTitle = "新增数据字典项";
      this.addDictValueDialogVisible = true;
      this.dictValue.typeId = this.$route.params.id;
      this.dictValue.value = '';
      this.dictValue.desc = '';
    },
    edit(id) {
      // TODO: 编辑逻辑
      this.dialogTitle = "编辑数据字典项";
      console.log(id)
      doGet("/system/dict/value/" + encodeURI(id)).then(resp => {
        if (resp.data.code === 200) {
          this.dictValue = resp.data.data;
          this.addDictValueDialogVisible = true;
        }
      });
    },
    del(id) {
      // TODO: 删除逻辑
      msgConfirm("确定要删除吗？").then(()=>{
        doDelete("/system/dict/value/delete/" + encodeURI(id)).then(resp => {
          if(resp.data.code === 200) {
            msgTip("删除成功","success");
            this.reload();
          }
        })
      }).catch(() => {
        msgTip("取消了删除", 'warning');
      })
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection.map(item => item.id);
    },

    addDictValueSubmit() {
      this.$refs.dictTypeRefForm.validate(valid => {
        if(valid) {
          if(this.dictValue.id > 0) {
            doPut("/system/dict/value/update", this.dictValue).then(resp => {
              if(resp.data.code === 200) {
                msgTip("编辑数据字典项成功","success");
                this.reload();
              } else {
                msgTip("编辑数据字典项失败","error");
              }
            });
          } else {
            doPost("/system/dict/value/add", this.dictValue).then(resp => {
              if(resp.data.code === 200) {
                msgTip("新增数据字典项成功","success");
                this.reload();
              }
            });
          }
        }
      });
    },


    /* 新增编辑数据字典的校验逻辑 */
    validateDictValue(rule,value,callback) {
      // 编辑时不可以编辑为除自己外已存在的值
      // 新增时不可以新增已存在的数据字典项
      if (this.dictValue.id && this.dictValues.some(item => item.value === value && item.id !== this.dictValue.id)) {
        callback(new Error("数据字典项已存在"));
      } else if (!this.dictValue.id && this.dictValues.some(item => item.value === value)) {
        callback(new Error("数据字典项已存在"));
      } else {
        callback();
      }
    }
  },
  mounted(){
    this.getDictValues();
    this.getDictType();
  },
  watch: {
    $route(to, from) {
      // 如果路由参数变化，重新获取字典详情
      if (to.params.id !== from.params.id) {
        this.getDictValues();
        this.getDictType();
      }
    }
  }
}
</script>

<template>
  <h2 class="title">{{ dictType.type }} 字典项详情：</h2>
  <el-divider/>
  <div class="op-btn">
    <el-button type="danger" class="btn" @click="batchDelDictType">批量删除</el-button>
    <el-button type="primary" class="btn" @click="addValue">新增</el-button>
    <el-button type="info" class="btn" @click="$router.back()">返回</el-button>
  </div>
  <el-table
      :data="dictValues"
      style="width:100%"
      @selection-change="handleSelectionChange"
      class="custom-table"
      border
      stripe>
    <el-table-column type="selection" width="50" />
    <el-table-column type="index" label="序号" width="80" />
    <el-table-column prop="value" label="字典值" />
    <el-table-column prop="desc" label="值描述" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" @click="edit(scope.row.id)" size="small">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)" size="small">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 新增数据字典项 -->
  <el-dialog :title="dialogTitle" v-model="addDictValueDialogVisible" width="35%" :close-on-click-modal="false">
    <el-form ref="dictTypeRefForm" :model="dictValue" label-width="130px" :rules="dictValueRules">
      <!--   添加一个隐藏项，它的值永远绑定typeId为路由参数值   -->
      <el-form-item prop="typeId">
        <el-input v-model="dictValue.typeId" type="hidden"></el-input>
      </el-form-item>
      <el-form-item label="数据字典项" prop="value">
        <el-input v-model="dictValue.value" placeholder="请输入数据字典项" clearable></el-input>
      </el-form-item>
      <el-form-item label="数据字典项描述" prop="desc">
        <el-input v-model="dictValue.desc" placeholder="请输入数据字典项描述" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDictValueDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addDictValueSubmit">提交</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<style scoped>
  .title {
    margin-bottom: 20px;
  }
  .query-form {
    .el-input {
      width: 220px;
    }
    .el-select {
      width: 220px;
    }
  }

  .op-btn {
    margin-top: 20px;
    display: flex;
    justify-content: flex-start;
  }

  .custom-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
  }
  .custom-table ::v-deep th {
    background-color: rgb(190, 190, 190) ; /* 背景色 */
    color: #303133;
    font-weight: bold; /* 加粗字体 */
  }

  .custom-table ::v-deep th,
  .custom-table ::v-deep td {
    padding: 10px;
    text-align: left;
  }


  .custom-table ::v-deep tr:nth-child(even) {
    background-color: #f9f9f9;
  }

  .custom-table ::v-deep tr:hover {
    background-color: #f1f1f1;
  }


  .pagination {
    margin-top: 20px;
  }

  .button-column {
    display: flex;
    flex-direction: column;
    gap: 5px; /* 设置按钮之间的间距 */
    .el-button {
      width: 80px;
      margin-left: 0 !important;
    }
  }
</style>